
#ifndef TCP_CLIENT_H_
#define TCP_CLIENT_H_
#define MAX 64
#include<fstream>
#define DEGBUG 1
#if DEGBUG
#define LOG(s) cout<<s<<endl;
#else
#define LOG(s) /*Comment*/
#endif
#include<iostream>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<string.h>

using namespace std;


class TCP_Client
{
	int sockfd;
	struct sockaddr_in servaddr;
	char  inputfile[MAX];			//Compressed .rir file
	char outputfile[MAX];			//Decompressed original file
	int Decompress();
public :
	TCP_Client(int port_number, const char * ip_addr);
	int Socket();
	int Connect();
	int SendRequestandRecieve(const char *filename);
	void DisplayFile();
	int Close();
	~TCP_Client();
};

TCP_Client::~TCP_Client(){LOG(__func__);}
TCP_Client::TCP_Client(const int port_number, const char *ip_addr)
{
	LOG(__func__);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port_number);
	inet_pton(AF_INET, ip_addr, &servaddr.sin_addr);

}
int TCP_Client::Socket()
{
	LOG(__func__);
	return (sockfd = socket(AF_INET, SOCK_STREAM, 0));
}
int TCP_Client::Connect()
{
	LOG(__func__);
	return connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
}
int TCP_Client::SendRequestandRecieve(const char *filename)
{
	LOG(__func__);
	
	cout << "Here: 1";
	strcpy(inputfile, filename);
	cout << "Here: 2";
	strcat(inputfile, ".rir");
	cout << "Here: 3";
	/*write(sockfd, filename, strlen(filename));
	char buf[MAX] = {'\0'};
	ofstream compressedfile;
	strcat(file,".rir");
	
	compressedfile.open(file);
	
	int n = 0;
	while((n = read(sockfd, buf, sizeof(buf))) > 0)
	{
		buf[n] = 0;
		compressedfile<<buf;
	}
	compressedfile.close();
	*/

	 ssize_t n;
    	char sendline[MAX], recvline[MAX];
    	
   	write(sockfd, filename, strlen(filename)); 
   	int compressedfile = open(inputfile, O_WRONLY | O_CREAT, 0777);

   	while((n = read(sockfd, recvline, sizeof(recvline)))>0)
	   write(compressedfile, recvline, n);
   	close(compressedfile);	

	Decompress();

}
int TCP_Client::Decompress()
{
	LOG(__func__);

	int len = strlen(inputfile);
	int status = -1;

	strncpy(outputfile, inputfile, len-4); //file will end with .rir and the output file is without .rir extension.
	outputfile[len-4] = '\0';
	cout << "inputfile = " << inputfile << endl << endl;
	cout << "outputfile = " << outputfile << endl << endl;;
	pid_t childpid = fork();
	if(childpid == 0)
	{
		
		execl("/home/nsatvik/Projects/DC_Project/DCP-v8.0/Client/unhuff","Decompressor", inputfile, outputfile, (char*) NULL);

	}
	if(waitpid(childpid,&status,0))
		perror("waitpid error:");
	return 1;
}
void TCP_Client::DisplayFile()
{
	LOG(__func__);
	ifstream in;
	in.open(outputfile);
	char ch;
	while((ch = in.get()) != EOF)
	{
		cout<<ch;
	}
	in.close();
}
int TCP_Client::Close()
{
	LOG(__func__);
	return close(sockfd);
}

#endif /* TCP_CLIENT_H_ */

